package cn.itcast.cd.action;

import java.util.List;

import cn.itcast.cd.dao.IPermissionDao;
import cn.itcast.cd.domain.Permission;
import cn.itcast.cd.domain.Role;
import cn.itcast.cd.service.IPermissionService;
import cn.itcast.cd.service.IRoleService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class RoleAction extends ActionSupport {

	
	private IRoleService roleService;
	private IPermissionService permissionService;
	public void setPermissionService(IPermissionService permissionService) {
		this.permissionService = permissionService;
	}

	private Permission permission = new Permission();
	public Permission getPermission() {
		return permission;
	}

	private Role role = new Role();
	
	
	public Role getRole() {
		return role;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	public String save(){
		//System.out.println(role.getId()+","+permission.getId());
		if(role.getId()==null){
			roleService.save(role);	
		}else if(role.getId()!=null && permission.getId()!=null){
			
			//这个就专门处理给角色添加权限.
			permission = permissionService.get(permission.getId());
			//System.out.println(permission);
			role = roleService.get(role.getId());
			//System.out.println(role);
			role.getPermissions().add(permission);
			roleService.update(role);
			return NONE;
		}else{
			roleService.update(role);
		}
		return SUCCESS;
	}
	
	public String delete(){
		roleService.delete(role.getId());
		return SUCCESS;
	}
	
	public String list(){
		String conditions = "SELECT r FROM Role r WHERE 1=?";
		List<Role> roles = roleService.queryEntity(conditions, new Object[]{1});
		ActionContext.getContext().put("roles", roles);
		return "list";
	}
	
}
